package com.example.mvvmcoroutineexample.ui.main

import android.os.Bundle
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.core.view.isVisible
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.mvvmcoroutineexample.R
import com.example.mvvmcoroutineexample.databinding.FragmentLoginBinding
import com.example.mvvmcoroutineexample.viewmodels.LoginViewModel
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch

/**
 * A simple [Fragment] subclass.
 * Use the [Login.newInstance] factory method to
 * create an instance of this fragment.
 */
class Login : Fragment() {

    private var _binding: FragmentLoginBinding? = null
    private val binding: FragmentLoginBinding
        get() = _binding!!
    private val viewModel: LoginViewModel by viewModels<LoginViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentLoginBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        binding.editUsername.doAfterTextChanged {
//            viewModel.userNameEntered(it?.toString().orEmpty())
//        }
//        binding.editPassword.doAfterTextChanged {
//            viewModel.passwordEntered(it?.toString().orEmpty())
//        }
        binding.buttonLogin.setOnClickListener {
            val userName: String = binding.editUsername.text.toString()
            val password: String = binding.editPassword.text.toString()
            viewModel.login(userName, password)
        }
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                launch {
                    binding.editUsername.textFlow().collect {
                        viewModel.userNameEntered(it)
                    }
                }
                launch {
                    binding.editPassword.textFlow().collect {
                        viewModel.passwordEntered(it)
                    }
                }
                launch {
                    viewModel.uiState.collect {
                        with(binding) {
                            buttonLogin.isEnabled = it.isButtonEnabled
                            progressCircular.isVisible = it.isProgressVisible
                        }
                    }
                }
                launch {
                    viewModel.authMessage.collect {
                        Snackbar.make(requireView(), it, Snackbar.LENGTH_LONG).show()
                    }
                }
            }
        }
    }

    fun EditText.textFlow(): Flow<String> = callbackFlow {
        val watcher: TextWatcher = doAfterTextChanged {
            trySend(it?.toString().orEmpty())
        }
        awaitClose {
            this@textFlow.removeTextChangedListener(watcher)
        }
    }
}